﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using SystemX.Services;
using SystemX.Utility;

namespace SystemX.Web.Infrastructure
{
	public class SQLCommandX:ICacheable
	{
		#region member variables
		/// <summary>
		/// sql命令ID
		/// </summary>
		public string CmdID { get; set; }
		/// <summary>
		/// 描述
		/// </summary>
		public string CmdDesc { get; set; }
		public string SqlBody { get; set; }
		public DateTime ModifiedOn { get; set; }
		public string ModifiedBy { get; set; }

		private static object _SyncRoot = new object();
		private static IList<SQLCommandX> commands;
		/// <summary>
		/// Gets an unsorted list of all Categories.
		/// </summary>
		public static IList<SQLCommandX> Commands
		{
			get
			{
				if (commands == null)
				{
					lock (_SyncRoot)
					{
						if (commands == null)
						{
							commands = GetAll();
						}
					}
				}

				return commands;
			}
		}
		static string FilePath{
			get
			{
				var retVal = string.Empty;
				if (!ConfigurationManager.AppSettings.AllKeys.Contains("SQLCommands"))
				{
					retVal = "~/App_Data/cfg/SQLCommands.xml";
				}
				else
				{
					retVal= ConfigurationManager.AppSettings["SQLCommands"];
				};
				if (Utils.AppIsRunOnWeb) {
					retVal = System.Web.HttpContext.Current.Server.MapPath(retVal);
				}
				return retVal;
			}
		}
		#endregion

		#region Methods
		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public static IList<SQLCommandX> GetAll()
		{
			var retVal = new List<SQLCommandX>();
			if (!File.Exists(FilePath))
			{
				retVal.Add(new SQLCommandX { 
					CmdID="DummySQL",
					CmdDesc="test sql",
					SqlBody="select * from test;"
				});
				XmlUtil.ToXMLDoc<List<SQLCommandX>>(retVal).Save(FilePath);
			}
			else
			{
				retVal=XmlUtil.DeserializeFromFile<List<SQLCommandX>>(FilePath);
			}
			return retVal;
		}
		/// <summary>
		/// Get a record
		/// </summary>
		/// <param name="expressID"></param>
		/// <returns></returns>
		public static SQLCommandX Get(string cmdid)
		{
			return Commands.FirstOrDefault(x => x.CmdID == cmdid);
		}
		
		#endregion

		#region ICacheable Members

		public void ClearCache()
		{
			commands = null;
		}

		#endregion
	}
}
